<template>
  <div id="cesiumContainer"></div>
  <div class="tool-box" v-if="false">
    <el-scrollbar height="650px">
      <div class="tool-box-item" @click="addTileset('old')">新三角滩</div>
      <div class="tool-box-item" @click="addTileset('new')">旧三角滩</div>
      <div
        class="tool-box-item"
        @click="oepnTerrain"
        :style="{ backgroundColor: terrainState ? 'rgba(50,255,130,.5)' : '' }"
      >
        <span
          class="oepn-terrain"
          :style="{ color: terrainState ? 'red' : 'green' }"
          >{{ terrainState ? "关闭" : "打开" }}</span
        >地形
      </div>
      <div
        class="tool-box-item"
        :style="{
          backgroundColor: depthTestState ? 'rgba(50,255,130,.5)' : '',
        }"
        @click="depthTest"
      >
        深度监测
      </div>
      <div
        class="tool-box-item"
        :style="{ backgroundColor: lightInter ? 'rgba(50,255,130,.5)' : '' }"
        @click="openLight"
      >
        光照({{ lightTime }}点)
      </div>
      <div class="tool-box-item" @click="addModel">
        {{ entity ? "更换" : "加载" }}模型
      </div>
      <div class="tool-box-item" @click="removeModel" v-show="entity">
        移除模型
      </div>
      <div class="tool-box-item" @click="getFlight">
        {{ flightEntity ? "关闭飞行" : "开始飞行" }}
      </div>
      <div
        class="tool-box-item"
        @click="animationStart"
        v-if="flightEntity"
        :style="{
          backgroundColor: animationState ? 'rgba(50,255,130,.5)' : '',
        }"
      >
        {{ animationState ? "暂停" : "开始" }}
      </div>
      <div
        class="tool-box-item"
        @click="loopAnimation"
        v-if="flightEntity"
        :style="{ backgroundColor: animationLoop ? 'rgba(50,255,130,.5)' : '' }"
      >
        循环
      </div>
      <div class="tool-box-item" v-if="flightEntity" @click="speedUp">加速</div>
      <div class="tool-box-item" v-if="flightEntity" @click="speedDown">
        减速
      </div>
      <div
        class="tool-box-item"
        @click="drawPoi"
        :style="{ backgroundColor: drawPoiState ? 'rgba(50,255,130,.5)' : '' }"
      >
        画点
      </div>
      <div class="tool-box-item" @click="addCloud">云朵</div>
      <div class="tool-box-item" @click="changeWeidu">切换23维</div>
      <div class="tool-box-item" @click="addCQjson">重庆矢量</div>
      <input
        class="tool-box-item"
        style="width: 100%"
        placeholder="经度"
        v-model="lngText"
      />
      <input
        class="tool-box-item"
        style="width: 100%"
        placeholder="纬度"
        v-model="latText"
      />
      <input
        class="tool-box-item"
        style="width: 100%"
        placeholder="角度"
        v-model="pitText"
      />
      <div class="tool-box-item" @click="flyTo">移动</div>
      <div class="tool-box-item" @click="flowLine2">流动线</div>
      <div class="tool-box-item" @click="flowLine">流动线1</div>
      <div class="tool-box-item" @click="addBillboard">billboard</div>
    </el-scrollbar>
  </div>

  <div class="tool-box" v-if="true">
    <el-scrollbar height="650px">
      <div class="tool-box-item" @click="homeView">初始视角</div>
      <!-- <div class="tool-box-item" @click="addLayer">影像</div> -->
      <div class="tool-box-item" @click="addTile">倾斜</div>
      <div class="tool-box-item" @click="addPois">点位</div>
      <div class="tool-box-item" @click="addLzbjson">拦渣坝</div>
      <div class="tool-box-item" @click="addShuixi">水系</div>
      <div class="tool-box-item" @click="addBianjiu">秀山县界</div>

      <div
        class="tool-box-item"
        @click="oepnTerrain"
        :style="{ backgroundColor: terrainState ? 'rgba(50,255,130,.5)' : '' }"
      >
        <span
          class="oepn-terrain"
          :style="{ color: terrainState ? 'red' : 'green' }"
          >{{ terrainState ? "关闭" : "打开" }}</span
        >地形
      </div>
      <div class="tool-box-item" @click="changeWeidu">切换23维</div>
      <div class="tool-box-item" @click="addline">流动线水流</div>
      <div class="tool-box-item" @click="flowLine">流动线方向</div>

      <div class="tool-box-item" @click="addLeftClickEvent">点击事件</div>
    </el-scrollbar>
  </div>
</template>
<script name='Global'>
import * as Cesium from "cesium";
import DefaultGlobe from "./default-globe.js";
import $ from "jquery";
import "./flowline3D.js";
import "./flowline2D.js";

export default {
  data() {
    return {
      viewer: null,
      imagerylayer: null,
      tileset: null,
      pois: null,
      shuixi: null,
      xsbj: null,
      lanzhaba: null,

      terrainState: false,
      lightInter: null,
      lightTime: 8,
      entity: null,
      modelArr: [
        {
          model_name: "Toycar",
          model_url: "../data/glb/toy_car.glb",
          model_height: 200,
        },
        {
          model_name: "WoodBall",
          model_url: "../data/glb/wood_ball.glb",
          model_height: 2000,
        },
        {
          model_name: "Air",
          model_url: "../data/glb/Cesium_Air.glb",
          model_height: 2000,
        },
        {
          model_name: "Man",
          model_url: "../data/glb/Cesium_Man.glb",
          model_height: 10,
        },
        {
          model_name: "Balloon",
          model_url: "../data/glb/CesiumBalloonKTX2.glb",
          model_height: 1000,
        },
        {
          model_name: "MilkCar",
          model_url: "../data/glb/CesiumMilkTruck.glb",
          model_height: 50,
        },
        {
          model_name: "Pawns",
          model_url: "../data/glb/Pawns.glb",
          model_height: 200,
        },
      ],
      modelIndex: 0,
      // 飞行飞机
      flightEntity: null,
      // 深度监测
      depthTestState: false,
      // 动画state
      animationState: false,
      // 动画循环
      animationLoop: false,
      // 画点 开启/关闭
      drawPoiState: false,
      // 输入的经纬度
      lngText: "",
      latText: "",
      pitText: "",
      flowRoad: null,
      flowline1: null,
      flowline2: null,
    };
  },
  methods: {
    homeView() {
      this.viewer.camera.flyTo({
        destination: Cesium.Cartesian3.fromDegrees(
          109.096043,
          28.294772,
          150000
        ),
        orientation: {
          heading: Cesium.Math.toRadians(348.4202942851978),
          pitch: Cesium.Math.toRadians(-89.74026687972041),
          roll: Cesium.Math.toRadians(0),
        },
        complete: function callback() {
          // 定位完成之后的回调函数
        },
      });
    },
    // http://localhost:8099/geoserver/xiushan/wms?service=WMS
    // &version=1.1.0&request=GetMap&layers=xiushana:meng1&styles=&bbox=585
    // 477.3025,3145429.51,585894.3625,3145805.51&width=768&height=692&srs=EPSG:404000&format=application/openlayers
    addLayer() {
      this.imagerylayer = new Cesium.WebMapServiceImageryProvider({
        url: "http://localhost:8099/geoserver/xiushan/wms",
        layers: "xiushan:meng1",
        parameters: {
          service: "WMS",
          format: "image/png",
          transparent: true,
          version: "1.1.0",
        },
      });
      this.viewer.imageryLayers.addImageryProvider(this.imagerylayer);
      // this.viewer.imageryLayers.add(this.imagerylayer);
      this.viewer.flyTo(this.imagerylayer);
    },
    addPois() {
      if (this.pois) {
        this.pois.show = !this.pois.show;
        if (this.pois.show) {
          process.viewer.flyTo(this.pois);
        }
        return;
      }
      Cesium.GeoJsonDataSource.load("data/json/pois.geojson", {
        clampToGround: true,
      }).then((dataSource) => {
        this.pois = dataSource;
        process.viewer.dataSources.add(dataSource);
        dataSource.entities.values.map((entity) => {
          let type = entity._properties._jcsblx._value;
          let option = {
            image: require("@/asset/img/poi1.png"), //修改图片样式
            scale: 0.5, //图片缩放大小
            zIndex: 99,
          };
          if (type == "水质监测") {
            option.image = require("@/asset/img/图标/水质监测.png");
          } else if (type == "位移基准站") {
            option.image = require("@/asset/img//图标/水质监测.png");
          } else if (type == "监控") {
            option.image = require("@/asset/img/图标/监控.png");
          } else if (type == "气象站") {
            option.image = require("@/asset/img/图标/气象站.png");
          } else if (type == "位移") {
            option.image = require("@/asset/img//图标/水质监测.png");
          } else if (type == "滤液收集池") {
            option.image = require("@/asset/img/图标/滤液收集池.png");
          } else if (type == "拦渣坝") {
            option.image = require("@/asset/img/图标/拦渣坝.png");
          }
          entity.billboard = option;

          entity.label = new Cesium.LabelGraphics({
            text: type,
            font: "14px Arial",
            fillColor: Cesium.Color.WHITE,
            outlineColor: Cesium.Color.BLACK,
            outlineWidth: 2,
            horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
            verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
            eyeOffset: new Cesium.Cartesian3(0, 0, -10000),
            pixelOffset: new Cesium.Cartesian2(0, -20), // 调整标签位置
            // zIndex:99
          });
        });
      });
    },
    addline() {
      if (this.flowRoad) {
        this.flowRoad.show = !this.flowRoad.show;
        if (this.flowRoad.show) {
          process.viewer.flyTo(this.flowRoad);
        }
        return;
      } else {
        let linePois = [
          [108.8732454, 28.4222152, 422.93],
          [108.8734547, 28.4220337, 417.79],
          [108.8734915, 28.4216904, 413.85],
          [108.8736085, 28.4216161, 414.07],
          [108.8738381, 28.4217561, 414.11],
          [108.8739036, 28.421861, 413.66],
          [108.8739909, 28.421919, 413.5],
          [108.8741865, 28.4219257, 412.97],
          [108.8742237, 28.421943, 412.57],
          [108.874635, 28.4222858, 411.96],
          [108.874882, 28.4224963, 411.3],
          [108.8752771, 28.4228148, 408.14],
          [108.875415, 28.4228914, 405.73],
          [108.8755606, 28.423025, 406.72],
          [108.8755597, 28.4230673, 406.76],
          [108.8754136, 28.4231449, 406.65],
          [108.8753001, 28.4232531, 406.35],
          [108.8752195, 28.4233609, 406.19],
          [108.8751456, 28.4234697, 406.15],
          [108.8750801, 28.4235992, 406.37],
          [108.8750238, 28.4237647, 405.12],
          [108.8751191, 28.4238035, 402.11],
          [108.8751924, 28.4237453, 398.81],
          [108.8753006, 28.423472, 397.8],
          [108.875669, 28.423249, 397.39],
          [108.8757789, 28.4232718, 396.56],
          [108.8758589, 28.4232747, 396.08],
          [108.8759193, 28.4233533, 393.74],
          [108.8760585, 28.4234799, 390.27],
          [108.8760716, 28.4236527, 397.03],
          [108.8758651, 28.4240362, 393.65],
          [108.8758805, 28.4240485, 392.79],
          [108.8758151, 28.4241736, 393.65],
          [108.8757597, 28.4242435, 394.16],
          [108.8756609, 28.4243214, 393.58],
        ];
        linePois.forEach((poi, index) => {
          linePois[index] = Cesium.Cartesian3.fromDegrees(...poi);
        });

        this.flowRoad = process.viewer.entities.add({
          id: "flowline",
          polyline: {
            positions: linePois,
            heightReference: Cesium.HeightReference.CLAMP_TO_GROUND, //贴地设置
            horizontalOrigin: Cesium.HorizontalOrigin.CENTER, // //相对于对象的原点（注意是原点的位置）的水平位置
            verticalOrigin: Cesium.VerticalOrigin.BOTTOM, //相对于对象的原点的垂直位置，BOTTOM时锚点在下，对象在上
            width: 10,
            // material: new Cesium.ImageLineMaterial3DProperty({
            material: new Cesium.ImageLineMaterial3DProperty({
              // image: require("@/asset/img/weave.png"),
              image: require("@/asset/img/arrow.png"),
              duration: 1000,
            }),
          },
        });
        process.viewer.flyTo(this.flowRoad);
      }
    },
    addTile() {
      if (this.tileset) {
        this.tileset.show = !this.tileset.show;
        process.viewer.flyTo(this.tileset);
        return;
      }

      let tilesetUrl = "data/3dtiles/meng1/tileset.json";
      Cesium.Cesium3DTileset.fromUrl(tilesetUrl).then((tileset) => {
        this.tileset = tileset;
        process.viewer.scene.primitives.add(tileset);
        process.viewer.flyTo(tileset);
      });
    },
    addShuixi() {
      if (this.shuixi) {
        this.shuixi.show = !this.shuixi.show;
      } else {
        Cesium.GeoJsonDataSource.load("data/json/shuixi.geojson").then(
          (dataSource) => {
            this.shuixi = dataSource;
            this.viewer.dataSources.add(dataSource);
            dataSource.entities.values.forEach((entity) => {
              if (entity.polyline) {
                // 检查是否有polyline属性
                entity.polyline.material = Cesium.Color.BLUE.withAlpha(1); // 设置线的颜色，带透明度
                entity.polyline.width = 2; // 设置线的宽度
              }
            });
          }
        );
      }
    },
    addBianjiu() {
      if (this.xsbj) {
        this.xsbj.show = !this.xsbj.show;
      } else {
        Cesium.GeoJsonDataSource.load("data/json/xsbj.json").then(
          (dataSource) => {
            this.xsbj = dataSource;
            this.viewer.dataSources.add(dataSource);
            dataSource.entities.values.forEach((entity) => {
              if (entity.polygon) {
                entity.polygon.material = Cesium.Color.BLUE.withAlpha(0);
                entity.polygon.outlineColor =
                  Cesium.Color.fromCssColorString("rgba(0,0,0,0)");
                entity.polygon.outlineWidth = 5;

                const positions = entity.polygon.hierarchy._value.positions;
                entity.polyline = {
                  positions: positions,
                  width: 10,
                  material: Cesium.Color.fromBytes(255, 0, 0),
                };
              }
            });
          }
        );
      }
    },
    addLzbjson() {
      if (this.lanzhaba) {
        this.lanzhaba.show = !this.lanzhaba.show;
      } else {
        Cesium.GeoJsonDataSource.load("data/json/lanzhaba.geojson", {
          clampToGround: true,
          zIndex: 0,
        }).then((dataSource) => {
          this.lanzhaba = dataSource;
          this.viewer.dataSources.add(dataSource);
          dataSource.entities.values.forEach((entity) => {
            console.log(entity);
            if (entity.polygon) {
              entity.polygon.material =
                Cesium.Color.fromCssColorString("rgba(0,0,255,1)");
              entity.polygon.outlineColor =
                Cesium.Color.fromCssColorString("#0000ff");
              entity.polygon.outlineWidth = 15;
            }
          });
        });
      }
    },
    // 打开地形
    oepnTerrain() {
      this.terrainState = !this.terrainState;
      // // 打开
      // if (this.terrainState) {
      //   Cesium.createWorldTerrainAsync({
      //     requestWaterMask: true,
      //     requestVertexNormals: true,
      //   }).then((terrain) => {
      //     process.viewer.terrainProvider = terrain;
      //   });
      // }
      // // 关闭
      // else
      //   process.viewer.terrainProvider = new Cesium.EllipsoidTerrainProvider(
      //     {}
      //   );
    },
    // 深度监测
    depthTest() {
      this.depthTestState = !this.depthTestState;
      process.viewer.scene.globe.depthTestAgainstTerrain = this.depthTestState;
    },
    // 添加倾斜
    addTileset(str) {
      let tilesetUrl = "";
      if (str == "old") {
        tilesetUrl = "data/3dtiles/sanjiaotanjiu/tileset.json";
      } else {
        tilesetUrl = "data/3dtiles/sanjiaotanxin/tileset.json";
      }
      let tileset = Cesium.Cesium3DTileset.fromUrl(tilesetUrl).then(
        (tileset) => {
          process.viewer.scene.primitives.add(tileset);
          process.viewer.flyTo(tileset);
        }
      );
    },
    // 添加模型 glb
    addModel() {
      if (this.entity) {
        process.viewer.entities.remove(this.entity);
      }
      let model = this.modelArr[this.modelIndex];
      this.modelIndex++;
      const hpr = new Cesium.HeadingPitchRoll(135, 0, 0);
      const position = Cesium.Cartesian3.fromDegrees(
        106.501377,
        29.661466,
        model.model_height
      );
      const orientation = Cesium.Transforms.headingPitchRollQuaternion(
        position,
        hpr
      );
      const modelMatrix = Cesium.Transforms.headingPitchRollToFixedFrame(
        position,
        hpr
      );
      this.entity = process.viewer.entities.add({
        name: model.model_name,
        position: position,
        orientation: orientation,
        minimumPixelSize: 64,
        modelMatrix: modelMatrix,
        model: {
          uri: model.model_url,
          minimumPixelSize: 128,
          maximumScale: 50000,
        },
      });
      // process.viewer.camera.flyTo({
      //   destination: Cesium.Cartesian3.fromDegrees(
      //     106.501377,
      //     29.630466,
      //     model.model_height
      //   ),
      // });
      process.viewer.trackedEntity = this.entity;
      // process.viewer.flyTo(this.entity);
    },
    // 移除模型
    removeModel() {
      process.viewer.entities.remove(this.entity);
      this.entity = null;
      process.viewer.trackedEntity = null;
    },
    // 打开光照
    openLight() {
      process.viewer.scene.globe.enableLighting =
        !process.viewer.scene.globe.enableLighting;
      if (process.viewer.scene.globe.enableLighting) {
        // 打开地形
        this.terrainState = true;

        // 倾斜 增加 阴影
        process.viewer.shadows = true;
        process.viewer.terrainShadows = Cesium.ShadowMode.RECEIVE_ONLY;
        // process.viewer.shadowMap.darkness = 0.02; //阴影透明度--越大越透明

        this.lightInter = setInterval(() => {
          let utc = Cesium.JulianDate.fromDate(
            new Date("2024/8/26 " + this.lightTime + ":00:00")
          ); //UTC
          process.viewer.clockViewModel.currentTime =
            Cesium.JulianDate.addHours(utc, 0, new Cesium.JulianDate()); //北京时间=UTC+8=GMT+8
          this.lightTime++;

          // 定时更改太阳位置
          if (this.lightTime == 25) {
            this.lightTime = 0;
          }
        }, 500);
      } else {
        process.viewer.shadows = false;
        process.viewer.terrainShadows = Cesium.ShadowMode.DISABLED;
        if (this.lightInter) {
          clearInterval(this.lightInter);
          this.lightInter = null;
        }
      }
    },
    // 点击事件
    addLeftClickEvent() {
      let canvas = process.viewer.scene.canvas;
      let handler = new Cesium.ScreenSpaceEventHandler(canvas);
      let drawState = handler.setInputAction((lclickment) => {
        let ellipsoid = process.viewer.scene.globe.ellipsoid;
        //var cartesian = LoadCesium.Viewer.camera.pickEllipsoid(lclickment.position, ellipsoid);
        let cartesian = process.viewer.scene.pickPosition(lclickment.position);
        if (cartesian) {
          let cartographic = ellipsoid.cartesianToCartographic(cartesian);
          let lon = Cesium.Math.toDegrees(cartographic.longitude).toFixed(7);
          let lat = Cesium.Math.toDegrees(cartographic.latitude).toFixed(7);
          //地理高度
          let height = (cartographic.height + 1).toFixed(2);
          //相机高度
          // let height =
          //   process.viewer.camera.positionCartographic.height.toFixed(0);
          //方向   围绕Z轴旋转
          let heading = Cesium.Math.toDegrees(
            process.viewer.camera.heading
          ).toFixed(2);
          //倾斜角度   围绕Y轴旋转
          let pitch = Cesium.Math.toDegrees(
            process.viewer.camera.pitch
          ).toFixed(2);
          //围绕X轴旋转
          let roll = Cesium.Math.toDegrees(process.viewer.camera.roll).toFixed(
            2
          );
          console.log("经纬度高程:" + lon + "," + lat + "," + height);
          if (this.drawPoiState) {
            process.viewer.entities.add({
              // fromDegrees（经度，纬度，高度，椭球，结果）从以度为单位的经度和纬度值返回Cartesian3位置
              position: Cesium.Cartesian3.fromDegrees(
                lon * 1,
                lat * 1,
                height * 1
              ),
              point: {
                pixelSize: 5,
                color: Cesium.Color.fromCssColorString("#ee0000"),
                outlineColor: Cesium.Color.fromCssColorString("#fff"),
                outlineWidth: 2,
                // 显示区间
                // distanceDisplayCondition: new Cesium.DistanceDisplayCondition(
                //   0,
                //   1500
                // ),
                // 是否显示
                show: true,
              },
            });
          }

          // console.log(
          //   "旋转角方向:heading:" + heading + "," + pitch + "," + roll
          // );
        }
      }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
    },
    // 画点
    drawPoi() {
      // 1.深度监测打开后 可以在地形上画点 否则 显示有问题
      // 2.可直接在倾斜上画点
      this.drawPoiState = !this.drawPoiState;
      if (this.drawPoiState) {
        this.addLeftClickEvent();
      }
    },
    // 计算飞行圆 设置时间轴
    computeCirclularFlight(lon, lat, radius, start, stop) {
      //设置时间轴在 轨迹时间内
      process.viewer.clock.startTime = start.clone();
      process.viewer.clock.stopTime = stop.clone();
      process.viewer.clock.currentTime = start.clone();
      //process.viewer.clock.clockRange = Cesium.ClockRange.LOOP_STOP; //时间循环
      process.viewer.clock.multiplier = 10;

      // process.viewer.timeline.zoomTo(start, stop);

      const property = new Cesium.SampledPositionProperty();

      let firstposition;
      for (let i = 0; i <= 360; i += 15) {
        let position;
        let radians = Cesium.Math.toRadians(i);
        let time = Cesium.JulianDate.addSeconds(
          start,
          i,
          new Cesium.JulianDate()
        );
        position = Cesium.Cartesian3.fromDegrees(
          lon + radius * 1.5 * Math.cos(radians),
          lat + radius * Math.sin(radians),
          Cesium.Math.nextRandomNumber() * 500 + 1750
        );
        if (i == 0) {
          firstposition = position;
        }

        // 当 飞机到起点时
        if (i == 360) {
          property.addSample(time, firstposition);
          break;
        } else {
          property.addSample(time, position);
        }

        //创建点
        process.viewer.entities.add({
          position: position,
          point: {
            pixelSize: 20,
            color: Cesium.Color.TRANSPARENT,
            outlineColor: Cesium.Color.YELLOW,
            outlineWidth: 3,
          },
        });
      }
      return property;
    },
    // 飞行轨迹 和 飞机模型
    getFlight() {
      // 关闭动画 关闭循环
      this.animationState = false;
      this.animationLoop = false;
      process.viewer.clock.shouldAnimate = this.animationState;
      process.viewer.clock.clockRange = Cesium.ClockRange.CLAMPED;

      if (this.flightEntity) {
        process.viewer.entities.removeAll();
        this.flightEntity = false;
        return;
      }
      // 开始时间
      const start = Cesium.JulianDate.fromDate(new Date(2024, 2, 25, 16));
      // 结束时间
      const stop = Cesium.JulianDate.addSeconds(
        start,
        360,
        new Cesium.JulianDate()
      );

      // 获取坐标 和 时间
      const position = this.computeCirclularFlight(
        106.501377,
        29.661466,
        0.03,
        start,
        stop
      );
      this.flightEntity = process.viewer.entities.add({
        // 完成一圈时间
        availability: new Cesium.TimeIntervalCollection([
          new Cesium.TimeInterval({
            start: start,
            stop: stop,
          }),
        ]),

        //路径
        position: position,

        //获取飞行方向
        orientation: new Cesium.VelocityOrientationProperty(position),

        // 加载飞机模型
        model: {
          uri: "../data/glb/Cesium_Air.glb",
          minimumPixelSize: 64,
        },

        // 飞行路径
        path: {
          resolution: 1,
          material: new Cesium.PolylineGlowMaterialProperty({
            glowPower: 0.1,
            color: Cesium.Color.YELLOW,
          }),
          width: 10,
        },
      });
      // process.viewer.camera.flyTo(106.501377, 29.661466,5000);
      process.viewer.camera.flyTo({
        destination: Cesium.Cartesian3.fromDegrees(
          106.501377,
          29.643466,
          15000
        ),
      });
    },
    // 开启/关闭动画
    animationStart() {
      this.animationState = !this.animationState;
      process.viewer.clock.shouldAnimate = this.animationState;
    },
    // 开启/关闭循坏
    loopAnimation() {
      this.animationLoop = !this.animationLoop;
      if (this.animationLoop) {
        // 开启循环
        process.viewer.clock.clockRange = Cesium.ClockRange.LOOP_STOP;
      } else {
        // 关闭循环
        process.viewer.clock.clockRange = Cesium.ClockRange.CLAMPED;
      }
    },
    // 加速(时间加快)
    speedUp() {
      process.viewer.clockViewModel.multiplier *= 2;
    },
    // 减速(时间减缓)
    speedDown() {
      process.viewer.clockViewModel.multiplier /= 2;
    },
    getColor(colorName) {
      return Cesium.Color[colorName.toUpperCase()];
    },
    // 云朵
    addCloud() {
      const position = Cesium.Cartesian3.fromDegrees(106.501377, 29.630466, 50);

      const clouds = process.viewer.scene.primitives.add(
        new Cesium.CloudCollection({
          noiseDetail: 16.0,
          noiseOffset: Cesium.Cartesian3.ZERO,
        })
      );

      const cloudParameters = {
        scaleWithMaximumSize: true,
        scaleX: 25,
        scaleY: 12,
        maximumSizeX: 25,
        maximumSizeY: 12,
        maximumSizeZ: 15,
        renderSlice: true, // if false, renders the entire surface of the ellipsoid
        slice: 0.36,
        brightness: 1.0,
        color: "White",
        colors: ["White", "Red", "Green", "Blue", "Yellow", "Gray"],
      };

      const cloud = clouds.add({
        position: position,
        scale: new Cesium.Cartesian2(
          cloudParameters.scaleX,
          cloudParameters.scaleY
        ),
        maximumSize: new Cesium.Cartesian3(
          cloudParameters.maximumSizeX,
          cloudParameters.maximumSizeY,
          cloudParameters.maximumSizeZ
        ),
        color: this.getColor(cloudParameters.color),
        slice: cloudParameters.renderSlice ? cloudParameters.slice : -1.0,
        brightness: cloudParameters.brightness,
      });

      process.viewer.camera.flyTo({
        destination: Cesium.Cartesian3.fromDegrees(106.501377, 29.630466, 200),
      });
      // process.viewer.camera.lookAt(position, new Cesium.Cartesian3(30, 30, -10));
    },
    //淹没分析
    floodAnalysis(positions, targertWaterHeight, waterHeight) {
      // waterHeight 起始高度
      // targertWaterHeight 终止高度
      process.viewer.entities.add({
        polygon: {
          hierarchy: new Cesium.PolygonHierarchy(positions),
          // CallbackProperty 不断调用
          extrudedHeight: new Cesium.CallbackProperty(() => {
            waterHeight += 0.5;
            if (waterHeight > targertWaterHeight) {
              waterHeight = targertWaterHeight;
            }
            return waterHeight;
          }, false),
          material: new Cesium.Color.fromBytes(64, 157, 253, 150),
          perPositionHeight: true,
        },
      });
    },
    // 加载重庆市矢量json文件
    addCQjson() {
      process.viewer.dataSources.add(
        Cesium.GeoJsonDataSource.load("data/json/chongqing.json")
      );
      this.pickEntity();
    },

    // 切换23维
    changeWeidu() {
      if (process.viewer.scene.mode === Cesium.SceneMode.SCENE3D) {
        process.viewer.scene.morphTo2D(0);
      } else {
        process.viewer.scene.morphTo3D(0);
      }
    },
    flyTo() {
      if (this.lngText && this.latText) {
        let lng = this.lngText * 1;
        let lat = this.latText * 1;
        let pitch = this.pitText * 1;
        process.viewer.camera.setView({
          destination: Cesium.Cartesian3.fromDegrees(lng, lat, 500),
          orientation: {
            // 指向
            heading: 0,
            // 视角
            pitch: pitch,
            roll: 0,
          },
        });
      }
    },
    // entity点击事件
    pickEntity() {
      let handler = new Cesium.ScreenSpaceEventHandler(
        process.viewer.scene.canvas
      );
      let selectEntity = new Cesium.Entity();
      let that = this;
      handler.setInputAction(function (movement) {
        let pick = process.viewer.scene.pick(movement.position);
        if (Cesium.defined(pick)) {
          let id = pick.id._id;
          //console.log(id);
          that.messBoxVisable(pick, handler);
          if (selectEntity == pick) {
            return;
          } else {
            if (typeof selectEntity.polygon != "undefined") {
              selectEntity.polygon.material =
                Cesium.Color.fromCssColorString("rgba(255,255,0,.4)");
              selectEntity.polygon.outlineWidth = 3;
            }
          }
          selectEntity = pick.id;
          selectEntity.polygon.material = Cesium.Color.LIME;
        }
      }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
    },
    messBoxVisable(pick, handler) {
      let id = pick.id;
      var infoDiv = `
      <div id="box">
        <div>区县: ${id._name}</div>
      </div>
      `;
      $("#cesiumContainer").append(infoDiv);
      $("#box").show();
      console.log(pick);
      $("#box").click(() => {
        console.log("aaaaaa");
      });
    },
    flowLine() {
      if (this.flowline1) {
        this.flowline1.show = !this.flowline1.show;
        if (this.flowline1.show) {
          this.viewer.flyTo(this.flowline1);
        }
        return;
      }
      // 自定义材质的
      if (Cesium.PolylineTrailLinkMaterialPropertyRoad1 == undefined) {
        function PolylineTrailLinkMaterialPropertyRoad1(color, duration) {
          this._definitionChanged = new Cesium.Event();
          this._color = undefined;
          this._colorSubscription = undefined;
          this.color = color;
          this.duration = duration;
          this._time = new Date().getTime();
        }
        Object.defineProperties(
          PolylineTrailLinkMaterialPropertyRoad1.prototype,
          {
            isConstant: {
              get: function () {
                return false;
              },
            },
            definitionChanged: {
              get: function () {
                return this._definitionChanged;
              },
            },
            color: Cesium.createPropertyDescriptor("color"),
          }
        );
        PolylineTrailLinkMaterialPropertyRoad1.prototype.getType = function (
          time
        ) {
          return "PolylineTrailLink";
        };
        PolylineTrailLinkMaterialPropertyRoad1.prototype.getValue = function (
          time,
          result
        ) {
          if (!Cesium.defined(result)) {
            result = {};
          }
          result.color = Cesium.Property.getValueOrClonedDefault(
            this._color,
            time,
            Cesium.Color.WHITE,
            result.color
          );
          result.time =
            ((new Date().getTime() - this._time) % this.duration) /
            this.duration;
          return result;
        };
        PolylineTrailLinkMaterialPropertyRoad1.prototype.equals = function (
          other
        ) {
          return (
            this === other ||
            (other instanceof PolylineTrailLinkMaterialPropertyRoad1 &&
              Property.equals(this._color, other._color))
          );
        };
        Cesium.PolylineTrailLinkMaterialPropertyRoad1 =
          PolylineTrailLinkMaterialPropertyRoad1;
        Cesium.Material.PolylineTrailLinkType = "PolylineTrailLink";
        Cesium.Material.PolylineTrailLinkImage = require("@/asset/img/arrow.png"); //道路样式的png
        Cesium.Material.PolylineTrailLinkSource =
          "czm_material czm_getMaterial(czm_materialInput materialInput)\n\
                                                {\n\
                                                    czm_material material = czm_getDefaultMaterial(materialInput);\n\
                                                    vec2 st = materialInput.st;\n\
                                                    vec4 colorImage = texture(image, vec2(fract(st.s - time), st.t));\n\
                                                    material.alpha = colorImage.a * color.a;\n\
                                                    material.diffuse = (colorImage.rgb+color.rgb)/2.0;\n\
                                                    return material;\n\
                                                }";
        Cesium.Material._materialCache.addMaterial(
          Cesium.Material.PolylineTrailLinkType,
          {
            fabric: {
              type: Cesium.Material.PolylineTrailLinkType,
              uniforms: {
                color: new Cesium.Color(1.0, 0.0, 0.0, 0.5),
                image: Cesium.Material.PolylineTrailLinkImage,
                time: 0,
                constantSpeed: 300,
                depthFailMaterial: true,
              },
              source: Cesium.Material.PolylineTrailLinkSource,
            },
            translucent: function (material) {
              return true;
            },
          }
        );
      }

      let linePois = [
        [108.8732454, 28.4222152, 422.93],
        [108.8734547, 28.4220337, 417.79],
        [108.8734915, 28.4216904, 413.85],
        [108.8736085, 28.4216161, 414.07],
        [108.8738381, 28.4217561, 414.11],
        [108.8739036, 28.421861, 413.66],
        [108.8739909, 28.421919, 413.5],
        [108.8741865, 28.4219257, 412.97],
        [108.8742237, 28.421943, 412.57],
        [108.874635, 28.4222858, 411.96],
        [108.874882, 28.4224963, 411.3],
        [108.8752771, 28.4228148, 408.14],
        [108.875415, 28.4228914, 405.73],
        [108.8755606, 28.423025, 406.72],
        [108.8755597, 28.4230673, 406.76],
        [108.8754136, 28.4231449, 406.65],
        [108.8753001, 28.4232531, 406.35],
        [108.8752195, 28.4233609, 406.19],
        [108.8751456, 28.4234697, 406.15],
        [108.8750801, 28.4235992, 406.37],
        [108.8750238, 28.4237647, 405.12],
        [108.8751191, 28.4238035, 402.11],
        [108.8751924, 28.4237453, 398.81],
        [108.8753006, 28.423472, 397.8],
        [108.875669, 28.423249, 397.39],
        [108.8757789, 28.4232718, 396.56],
        [108.8758589, 28.4232747, 396.08],
        [108.8759193, 28.4233533, 393.74],
        [108.8760585, 28.4234799, 390.27],
        [108.8760716, 28.4236527, 397.03],
        [108.8758651, 28.4240362, 393.65],
        [108.8758805, 28.4240485, 392.79],
        [108.8758151, 28.4241736, 393.65],
        [108.8757597, 28.4242435, 394.16],
        [108.8756609, 28.4243214, 393.58],
      ];
      linePois.forEach((poi, index) => {
        linePois[index] = Cesium.Cartesian3.fromDegrees(...poi);
      });

      let roadColor = new Cesium.Color.fromCssColorString("rgb(102,102,255)");
      let roadMaterial = new Cesium.PolylineTrailLinkMaterialPropertyRoad1(
        roadColor,
        15000
      );

      // 创建流动线对象
      this.flowline1 = this.viewer.entities.add({
        polyline: new Cesium.PolylineGraphics({
          material: roadMaterial,
          width: new Cesium.ConstantProperty(15), // 线宽
          arcType: Cesium.ArcType.GEODESIC,
          positions: linePois, //positions道路经过的坐标点集合
        }),
      });
    },
    // billBoard
    addBillboard() {
      process.viewer.entities.add({
        position: Cesium.Cartesian3.fromDegrees(106.583733, 29.56598),
        billboard: {
          image: require("@/asset/img/home.png"),
          scaleByDistance: new Cesium.NearFarScalar(1.5e2, 2.0, 1.5e7, 0.5),
          translucencyByDistance: new Cesium.NearFarScalar(
            1.5e2,
            1.0,
            1.5e7,
            0.2
          ),
        },
      });
    },
    // 流动线
    flowLine2() {
      if (this.flowline2) {
        this.flowline2.show = !this.flowline2.show;
      }
      // 激光材质类
      function LaserPolylineTrailLinkMaterialProperty(duration, color) {
        this._definitionChanged = new Cesium.Event();
        this._color = undefined;
        this._colorSubscription = undefined;
        this.color = color;
        this.duration = duration;
        this._time = new Date().getTime();
      }

      Object.defineProperties(
        LaserPolylineTrailLinkMaterialProperty.prototype,
        {
          isConstant: {
            get: function () {
              return false;
            },
          },
          definitionChanged: {
            get: function () {
              return this._definitionChanged;
            },
          },
          color: Cesium.createPropertyDescriptor("color"),
        }
      );

      LaserPolylineTrailLinkMaterialProperty.prototype.getType = function (
        time
      ) {
        return "PolylineTrailLink";
      };

      LaserPolylineTrailLinkMaterialProperty.prototype.getValue = function (
        time,
        result
      ) {
        if (!Cesium.defined(result)) {
          result = {};
        }
        result.color = Cesium.Property.getValueOrClonedDefault(
          this._color,
          time,
          Cesium.Color.WHITE,
          result.color
        );
        result.image = Cesium.Material.PolylineTrailLinkImage;
        result.time =
          ((new Date().getTime() - this._time) % this.duration) / this.duration;
        return result;
      };

      LaserPolylineTrailLinkMaterialProperty.prototype.equals = function (
        other
      ) {
        return (
          this === other ||
          (other instanceof LaserPolylineTrailLinkMaterialProperty &&
            Cesium.Property.equals(this._color, other._color))
        );
      };

      Cesium.LaserPolylineTrailLinkMaterialProperty =
        LaserPolylineTrailLinkMaterialProperty;
      Cesium.Material.PolylineTrailLinkType = "PolylineTrailLink";
      Cesium.Material.PolylineTrailLinkImage = require("@/asset/img/arrow2.png");
      Cesium.Material.PolylineTrailLinkSource =
        "czm_material czm_getMaterial(czm_materialInput materialInput)\n\
 { czm_material material = czm_getDefaultMaterial(materialInput); vec2 st = materialInput.st;\n\
    vec4 colorImage = texture(image, vec2(fract(st.s - time), st.t));\n\
     material.alpha = colorImage.a * color.a;\n\
     material.diffuse = (colorImage.rgb + color.rgb) / 2.0;\n\
     return material;}";
      Cesium.Material._materialCache.addMaterial(
        Cesium.Material.PolylineTrailLinkType,
        {
          fabric: {
            type: Cesium.Material.PolylineTrailLinkType,
            uniforms: {
              color: new Cesium.Color(1.0, 0.0, 0.0, 0.5),
              image: Cesium.Material.PolylineTrailLinkImage,
              time: 20,
            },
            source: Cesium.Material.PolylineTrailLinkSource,
          },
          translucent: function (material) {
            return true;
          },
        }
      );

      let pois = [
        [106.668109139395767, 29.569371909241603, 3000.0],
        [106.663360585168405, 29.578664200015474, 3000.0],
        [106.65445704599216, 29.593117174464002, 3000.0],
        [106.652379553517719, 29.594665584664231, 3000.0],
        [106.646443860733555, 29.592859103786772, 3000.0],
        [106.640508167949392, 29.590794514603971, 3000.0],
        [106.635759613722072, 29.590278360707039, 3000.0],
        [106.631307844133943, 29.592084887794194, 3000.0],
        [106.629230351659473, 29.596213971098383, 3000.0],
        [106.62626250526742, 29.604729671633457, 3000.0],
        [106.623591443514542, 29.611696528137522, 3000.0],
        [106.6215139510401, 29.616082820431707, 3000.0],
        [106.617062181451942, 29.61892090785307, 3000.0],
        [106.603410088048363, 29.620726921873523, 3000.0],
        [106.600145457017078, 29.61917891183753, 3000.0],
        [106.590648348562439, 29.614018706657102, 3000.0],
        [106.585603009695916, 29.610922456743626, 3000.0],
        [106.581151240107744, 29.605503790572921, 3000.0],
        [106.579964101550942, 29.599568726837894, 3000.0],
        [106.578480178354894, 29.59414945057145, 3000.0],
        [106.577886609076472, 29.590020282768421, 3000.0],
        [106.578480178354894, 29.583568119777926, 3000.0],
        [106.579964101550942, 29.580729037375644, 3000.0],
        [106.582338378664588, 29.57556686478193, 3000.0],
        [106.583822301860636, 29.573243800995328, 3000.0],
        [106.587086932891921, 29.568339379700269, 3000.0],
        [106.587086932891921, 29.561885830896021, 3000.0],
        [106.587086932891921, 29.559046138794749, 3000.0],
        [106.583525517221432, 29.553366515133629, 3000.0],
        [106.580557670829364, 29.549752042945777, 3000.0],
        [106.57610590124122, 29.547686572225931, 3000.0],
        [106.568389500621834, 29.546653821037356, 3000.0],
        [106.56601522350816, 29.546653821037356, 3000.0],
        [106.560673100002418, 29.545621059296678, 3000.0],
        [106.554737407218255, 29.545104674469346, 3000.0],
        [106.551472776186969, 29.544071896900888, 3000.0],
        [106.54583386804201, 29.543039108780881, 3000.0],
        [106.542866021649928, 29.54226451076654, 3000.0],
        [106.537820682783362, 29.542006310109539, 3000.0],
        [106.535149621030513, 29.540973500887095, 3000.0],
        [106.531588205359995, 29.536325728822341, 3000.0],
        [106.530401066803151, 29.534001762675736, 3000.0],
        [106.528917143607117, 29.529870135439019, 3000.0],
        [106.528917143607117, 29.526254823158311, 3000.0],
        [106.52802678968952, 29.513600212723823, 3000.0],
        [106.52802678968952, 29.511534003602424, 3000.0],
        [106.533962482473683, 29.508692897192947, 3000.0],
        [106.537227113504969, 29.507401458828987, 3000.0],
      ];

      pois.forEach((poi, index) => {
        pois[index] = Cesium.Cartesian3.fromDegrees(...poi);
      });

      this.flowline2 = process.viewer.entities.add({
        id: "line2",
        polyline: {
          positions: pois,
          width: 15,
          material: new Cesium.LaserPolylineTrailLinkMaterialProperty(
            1000,
            Cesium.Color.WHITE
          ),
        },
      });
    },
  },
  watch: {
    terrainState(newValue, oldValue) {
      if (newValue) {
        // 打开地形
        Cesium.createWorldTerrainAsync({
          requestWaterMask: true,
          requestVertexNormals: true,
        }).then((terrain) => {
          process.viewer.terrainProvider = terrain;
        });
      } else {
        // 关闭地形
        process.viewer.terrainProvider = new Cesium.EllipsoidTerrainProvider(
          {}
        );
      }
    },
  },
  mounted() {
    this.viewer = new Cesium.Viewer("cesiumContainer", {
      // 无网络时 必须关闭cesium提供的地形和影像数据 加载不出来
      // 地形图层
      // terrain: Cesium.Terrain.fromWorldTerrain(),
      // 影像更换
      //  imageryProvider:  new Cesium.UrlTemplateImageryProvider({
      //     url: ''
      //   }),
      //信息窗口
      infoBox: false,
      //显示查询按钮
      geocoder: false,
      //home按钮
      homeButton: false,
      //控制查看器的显示模式
      sceneModePicker: false,
      // 是否显示图层选择
      baseLayerPicker: false,
      //帮助按钮
      navigationHelpButton: false,
      //播放动画
      animation: false,
      // 时间线
      timeline: false,
      //全屏模式
      fullscreenButton: false,
      // 关闭点击绿色框
      selectionIndicator: false,
    });
    process.viewer = this.viewer;
    // viewer.extend(Cesium.viewerCesiumInspectorMixin);
    // cesium基本设置
    DefaultGlobe.cesiumDefaultModel(process.viewer); //调用方法
    // 手动开启地形
    // this.terrainState = true;
    // 关闭动画循环
    process.viewer.clock.clockRange = Cesium.ClockRange.CLAMPED;
    // 鼠标左键点击事件
    // this.addLeftClickEvent();
    this.addShuixi();
    this.addBianjiu();
  },
  beforeUnmount() {
    process.viewer.destroy();
  },
};
</script>
<style scoped>
.oepn-terrain {
  display: flex;
  align-items: center;
  justify-content: center;
}

.tool-box {
  position: absolute;
  left: 0;
  top: 0;
  padding: 5px;
  width: 200px;
  background-color: rgba(255, 255, 255, 0.6);
}

.tool-box-item {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 10px;
}

.tool-box-item:hover {
  background-color: rgba(255, 255, 255, 0.4);
  cursor: pointer;
}
</style>